package com.hunttown.mes.service;

import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.common.domain.Query;
import com.hunttown.mes.dao.TransportUserCardLogDao;
import com.hunttown.mes.domain.TransportUserCardLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * created by wangjunfu on 2021-02-25 10:59:16
 */
@Service
public class TransportUserCardLogService {

    private final static Logger logger = LoggerFactory.getLogger(TransportUserCardLogService.class);

    private final TransportUserCardLogDao transportUserCardLogDao;
    private final AHelpService helpService;

    @Autowired
    public TransportUserCardLogService(TransportUserCardLogDao transportUserCardLogDao, AHelpService helpService) {
        this.transportUserCardLogDao = transportUserCardLogDao;
        this.helpService = helpService;
    }

    /**
     * 新增
     *
     * @param transportUserCardLog 实体对象
     * @return 最新插入id
     */
    public TransportUserCardLog insert(TransportUserCardLog transportUserCardLog) {
        //api接口传进来是有值的
        if (transportUserCardLog.getEntId() == null)
            transportUserCardLog.setEntId(helpService.getEnterpriseId());
        if (transportUserCardLog.getAdminId() == null)
            transportUserCardLog.setAdminId(0);
        if (transportUserCardLog.getCreateTime() == null)
            transportUserCardLog.setCreateTime(new Date());
        if (transportUserCardLog.getStopFlag() == null)
            transportUserCardLog.setStopFlag(0);
        if (transportUserCardLog.getDeleteFlag() == null)
            transportUserCardLog.setDeleteFlag(0);

        return transportUserCardLogDao.insert(transportUserCardLog);
    }

    /**
     * 根据ID修改数据信息
     *
     * @param transportUserCardLog 实体对象
     * @return True or False
     */
    public Boolean updateInfoById(TransportUserCardLog transportUserCardLog) {
        if (transportUserCardLog.getEntId() == null) {
            transportUserCardLog.setEntId(helpService.getEnterpriseId());
        }
        return transportUserCardLogDao.updateInfoById(transportUserCardLog);
    }

    /**
     * 根据Query修改数据信息
     *
     * @param query 需要修改的字段 KV 格式
     * @return True or False
     */
    public Boolean updateInfoByQuery(Query query) {
        if (!query.containsKey("w_entId")) {
            query.put("w_entId", helpService.getEnterpriseId());
        }
        return transportUserCardLogDao.updateInfoByQuery(query);
    }

    /**
     * 根据ID获取记录信息
     *
     * @param id 主键id
     * @return 实体对象
     */
    public TransportUserCardLog selectById(Integer id) {
        return transportUserCardLogDao.selectById(id, helpService.getEnterpriseId());
    }

    public TransportUserCardLog selectByOrderIdForApi(String orderId) {
        return transportUserCardLogDao.selectByOrderIdForApi(orderId);
    }

    /**
     * 根据query取出一条记录，但是可能有多条记录，取最新的一条。
     *
     * @param query 查询条件 KV 格式
     * @return 实体对象
     */
    public TransportUserCardLog selectObjByQuery(Query query) {
        if (query == null || query.size() == 0) {
            return null;
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        List<TransportUserCardLog> list = selectByQuery(query);
        if (list == null || list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    //worker任务用，不涉及企业
    public TransportUserCardLog selectObjWithoutEnt(Query query) {
        if (query == null || query.size() == 0) {
            return null;
        }

        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }

        List<TransportUserCardLog> list = transportUserCardLogDao.selectByQuery(query);
        if (list == null || list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    /**
     * 根据条件获取List
     *
     * @param query 查询条件 KV 格式
     * @return 实体对象列表
     */
    public List<TransportUserCardLog> selectByQuery(Query query) {
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        return transportUserCardLogDao.selectByQuery(query);
    }

    /**
     * 根据条件获取记录总数
     *
     * @param query 查询条件 KV 格式
     * @return 总记录数
     */
    public Long countByQuery(Query query) {
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        return transportUserCardLogDao.countByQuery(query);
    }

    /**
     * 根据ID删除记录信息
     *
     * @param id 主键id
     * @return True or False
     */
    public Boolean deleteById(Integer id) {
        return transportUserCardLogDao.deleteById(id, helpService.getEnterpriseId());
    }

    /**
     * 新增（简单）
     *
     * @param rechargeType 消费类型：1充值 21生活缴费
     * @param recordId     计费日志记录ID
     * @param userId       用户ID
     * @param cardId       卡ID
     * @param cardNo       卡号
     * @param meterNumber  表号，当作订单号来使用
     * @param frontAmount  交易前金额
     * @param amount       交易金额
     * @param lastNum      起数
     * @param thisNum      止数
     * @param dSign        类型：1峰/2谷/3平/4尖
     * @param remark       交易备注
     * @param entId        企业ID
     * @return ID
     */
    public Integer insertSimple(
            Integer rechargeType,
            Integer recordId,
            Integer userId,
            String meterNumber,
            Integer cardId,
            String cardNo,
            BigDecimal frontAmount,
            BigDecimal amount,
            BigDecimal lastNum,
            BigDecimal thisNum,
            Integer dSign,
            String remark,
            Integer entId
    ) {
        Date defaultDate = DateConvertUtils.strToDate("1990-01-01");

        TransportUserCardLog dto = new TransportUserCardLog();
        if (entId != null && entId > 0) {
            dto.setEntId(entId);
        }
        dto.setTableId(138);
        dto.setRecordId(recordId);
        dto.setUserId(userId);
        dto.setCardId(cardId);
        dto.setCardNo(cardNo);
        dto.setCardType(1);
        dto.setStartTime(defaultDate);
        dto.setEndTime(defaultDate);
        dto.setOrderId(meterNumber);
        dto.setTradingNo("");
        dto.setRechargeType(rechargeType);
        dto.setFrontAmount(frontAmount);
        dto.setRechargeAmount(amount);
        dto.setRechargeRate(BigDecimal.ZERO);
        dto.setRateAmount(BigDecimal.ZERO);
        dto.setInvoiceNo("");
        dto.setFrontTimes(0);
        dto.setTimes(0);
        dto.setAppId("");
        dto.setPayCompay(0);
        dto.setMchId("");
        dto.setTradeType("");
        dto.setInvoiceType(0);
        dto.setTradeBody(remark + "：" + new BigDecimal(amount.toString()).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue() + "元");
        dto.setPreTradeTime(defaultDate);
        dto.setPreRequestUrl("");
        dto.setPrePayId("");
        dto.setPreCodUrl("");
        dto.setPreReturnCode("");
        dto.setPreReturnMsg("");
        dto.setRequestUrl("");
        dto.setNotifyUrl("");
        dto.setTradeTime(new Date());
        dto.setReturnCode("");
        dto.setReturnMsg("");
        dto.setNotifyTime(defaultDate);
        dto.setNotifyCode("");
        dto.setNotifyMsg("");
        dto.setLastNum(lastNum);
        dto.setThisNum(thisNum);
        dto.setUseNum(thisNum.subtract(lastNum));
        dto.setdSign(dSign);
        dto.setRemark(remark);
        dto.setOpIp("");
        dto.setBrowser("");
        dto.setStatus(1);   //PayStatusEnum.SUCCESS.getKey()
        dto.setAdminId(1);
        dto.setCreateTime(new Date());
        dto.setStopFlag(0);
        dto.setDeleteFlag(0);
        dto = insert(dto);

        if (dto != null) {
            return dto.getId();
        } else {
            return 0;
        }
    }

    //计算某个设备，一天的总费用
    public Float computeTotalAmount(Query query) {
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }
        return transportUserCardLogDao.computeTotalAmount(query);
    }

    //以map的形式返回数据
    public List<Map<String, String>> getMapDataByQuery(Query query, String element) {
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }
        return transportUserCardLogDao.getMapDataByQuery(query, element);
    }
}